from django.contrib.auth import authenticate, login, logout
from django.shortcuts import render_to_response
from django.template import RequestContext
from myproject.auth.models import User, AbstractUser, Student, Teacher, Institute, StudentForm, MyUserChangeFormName, MyUserChangeForm, TeacherForm, InstituteForm, Photo
import re
from django.http import HttpResponse
from myproject.myprofile.views import profile, getUser
from myproject.admins.views import admin
from django.contrib.auth.forms import PasswordChangeForm
from django.contrib.auth.forms import UserCreationForm
import sys
brand = 'BOMTAK'
from myproject.settings import STATIC_URL
'''
author: Nader
date: 16.02.12
desc: This is the home page, redirects you to the login, and logs out the user in case s/he is already logged in
params: HttpRequest request
'''
def index(request, forgotPass_success_msg=None, forgotPass_error_msg=None):
    if request.user.is_authenticated():
        if request.user.is_superuser:
            return admin(request)
        else: 
            return profile(request)
    return render_to_response('index.html', {'error_message':"start", 'form':UserCreationForm(),
                                             'forgotPass_success_msg':forgotPass_success_msg, 'forgotPass_error_msg':forgotPass_error_msg},
                               context_instance=RequestContext(request)) # error_message is used later on in the template to inform the user incase login is unsuccessful

'''
author:Nader
date: 16.02.12
desc: Checks username and password and acts accordingly
params: HttpRequest request
'''
def Login(request):
    try:
        username = request.POST['username']
        password = request.POST['password']
    except:
        return index(request)
    user = authenticate(username=username, password=password)
    
    if user is not None:
        if user.is_active:
            if user.is_superuser:
                login(request, user)
                return admin(request)
            else:
                abstract_user = AbstractUser.objects.get(user=user)
                if abstract_user.banned:
                    error_message = 'This account has been banned by the admin'
                    if abstract_user.banning_reason:
                        error_message += '\nReason: ' + abstract_user.banning_reason
                else:
                    login(request, user)
                    return index(request)
        else:
            # Return a 'disabled account' error message
            error_message = "Your account is disabled"
    else: 
        # Return an 'invalid account' error message
        error_message = "Username/Password combination is incorrect"
    return render_to_response('index.html', {'error_message':error_message, 'form':UserCreationForm()}, context_instance=RequestContext(request))

def Logout(request):
    logout(request)
    return index(request)

def Register(request):
    from myproject.auth.models import ActivationCode
    def emailValidation(email):
        if User.objects.filter(email=email): # this means that the email was found in the db. Error msg needs to be set now
                email_error = "This email address is already registered"
        elif not re.match(r'.+@.+[.].+.+', email):
            email_error = "Please enter a valid email address"
        else:
            email_error = '' # no error
        return email_error
    def codeValidation(code):
        activation_code = ActivationCode.objects.filter(code=code)
        code_error = None
        if activation_code:
            activation_code = ActivationCode.objects.get(code=code)
            if activation_code.abstract_user:
                code_error = "Activation code has already been used"
        else:
            code_error = "Incorrect activation code"
        return code_error

    email, email_error, userType_error = '', '', ''
    
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        email = request.POST['email']
        code = request.POST['code']
        # VALIDATION
        # 0. Code
        code_error = codeValidation(code)

        # 1. Email
        email_error = emailValidation(email)
        
        # 2. Category
        try:
            category = request.POST['user_type']
            userType_error = ''
        except KeyError:
            userType_error = "This field is required."
    
        # 3. USER 
        if form.is_valid() and not userType_error and not email_error and not code_error:
            # Create and save user
            user = User(username=form.cleaned_data['username'], email=email)
            user.set_password(form.cleaned_data['password2'])                
            user.save()
            user.backend = 'django.contrib.auth.backends.ModelBackend' 
            login(request, user)
            # Create and save abstract_user
            abstract_user = AbstractUser(user=user, reviews_notification=0, connections_notification=0, messages_notification=0)
            abstract_user.save()
            # Modify activation code by adding abstract_user
            activation_code = ActivationCode.objects.get(code=code)
            activation_code.abstract_user = abstract_user
            activation_code.save()

            # Create and save student/teacher/institute
            photo = Photo(path=STATIC_URL + 'uploaded/baseimage.jpg')
            photo.save()
            if category == 'student':
                Student(abstract_user=abstract_user, reviews=0, photo=photo).save()
                form = StudentForm()
            elif category == 'teacher':
                Teacher(abstract_user=abstract_user, reviews=0, photo=photo).save()
                form = TeacherForm()
            else:
                Institute(abstract_user=abstract_user, reviews=0, logo=photo).save()
                form = InstituteForm()
            return index(request)
    else:
        form = UserCreationForm()
    return render_to_response('index.html', {'form':form, 'email':email, 'email_error':email_error, 'code_error':code_error, 'userType_error':userType_error}, context_instance=RequestContext(request))

def emailPass(request):
    from django.core.mail import send_mail
    email = request.GET['user']
    try:
        newPass = User.objects.make_random_password()
        print 1
        user = User.objects.get(email=email)
        print 2
        user.set_password(newPass)
        print 3
        user.save()
        print 4
        msg = 'Dear ' + user.username + ',\n\n' + 'As per your request, your password has been reset, here is your new password: ' + newPass + '\n\nKeep on enjoying ' + brand + ' :)'
        send_mail('Password change', msg, 'BOMTAK', [user.email], fail_silently=False)
        forgotPass_success_msg = 'Password sent to: ' + user.email
        return index(request, forgotPass_success_msg=forgotPass_success_msg)
    except:
        forgotPass_error_msg = 'This email is not registered'
        return index(request, forgotPass_error_msg=forgotPass_error_msg)

def changePassword(request, page):
    success_message = None
    
    if request.method == 'POST':
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            request.user.set_password(form.clean_new_password2())
            request.user.save()
            success_message = 'Password changed successfully'
            return render_to_response(page, {'form':form, 'success_message':success_message}, context_instance=RequestContext(request))
    else:
        form = PasswordChangeForm(request.user)#(request.user)
    if not page == 'admins/changePassword.html':
        currentUser = getUser(request.user, False)
    else:
        currentUser = None
    return render_to_response(page, {'form':form, 'success_message':success_message, 'profileOwner':True, 'currentUser':currentUser}, context_instance=RequestContext(request))

def createDummyData(request):
    #ADMIN
    admin = User.objects.create_user('admin', 'alexannader@gmail.com', 'pass')
    admin.is_staff = True
    admin.is_superuser = True
    admin.save()
    
    photo = Photo(path=STATIC_URL + 'uploaded/baseimage.jpg')
    photo.save()
    #STUDENTS
    user = User.objects.create_user('Joesome', 'youssef.a.selim@gmail.com', 'pass')
    user.first_name = 'Youssef'
    user.last_name = 'Selim'
    user.save()
    abstract_user = AbstractUser(user=user, reviews_notification=0, connections_notification=0, messages_notification=0)
    abstract_user.save()
    joe = Student(abstract_user=abstract_user,
                  dob='1991-8-14', gender='Male', experience='Been playin the flute all ma life!',
                  favourite_genre='Rock, Alternatice Rock, and Jazz', instrument_played='Flute',
                  jamming_style='I like to mix it up, if you know what I mean', HOF=True, reviews=0, photo=photo)
    joe.save()
    
    photo = Photo(path=STATIC_URL + 'uploaded/baseimage.jpg')
    photo.save()
    user = User.objects.create_user('NAD', 'alexan.nader@gmail.com', 'pass')
    user.first_name = 'Nader'
    user.last_name = 'Alexan'
    user.save()
    abstract_user = AbstractUser(user=user, reviews_notification=0, connections_notification=0, messages_notification=0)
    abstract_user.save()
    nader = Student(abstract_user=abstract_user,
                    dob='1991-2-14', gender='Male', experience='None really, it is why I\'m here, I gotta learn!',
                    favourite_genre='Rap, Pop, and Rock', instrument_played='None, yet ;)', HOF=False, reviews=0, photo=photo)
    nader.save()
    
    #INSTITUES
    photo = Photo(path=STATIC_URL + 'uploaded/baseimage.jpg')
    photo.save()
    user = User.objects.create_user('SakiaCultureWheel', 'saqyia_culture_wheel@gmail.com', 'pass')
    user.first_name = 'Sakia'
    user.last_name = 'Culture Wheel'
    user.save()
    abstract_user = AbstractUser(user=user, reviews_notification=0, connections_notification=0, messages_notification=0)
    abstract_user.save()
    sakia = Institute(abstract_user=abstract_user, about='We opened a few years ago and have been giving young uprising musicians a chance to showcase their talents! We have multiple stages, top notch, our prices are reasonable and most importantly, we LOVE young musicians.',
                      open_on='Daily', open_from='8:00', open_to='21:00', HOF=True, reviews=0, logo=photo)
    sakia.save()
    
    photo = Photo(path=STATIC_URL + 'uploaded/baseimage.jpg')
    photo.save()
    user = User.objects.create_user('MusicValley', 'admin@musicvalley.com', 'pass')
    user.first_name = 'Music'
    user.last_name = 'Valley'
    user.save()
    abstract_user = AbstractUser(user=user, reviews_notification=0, connections_notification=0, messages_notification=0)
    abstract_user.save()
    musicvalley = Institute(abstract_user=abstract_user, about='We are a great studio for every musicians out there hoping to record their singles, or just come and jam! Pass by anytime and get a full tour of the place!',
                            open_on='Daily (except Friday)', open_from='10:00', open_to='22:00', HOF=False, reviews=0, logo=photo)
    musicvalley.save()
    
    #TEACHERS
    photo = Photo(path=STATIC_URL + 'uploaded/baseimage.jpg')
    photo.save()
    user = User.objects.create_user('Sioufy', 'joesioufy@gmail.com', 'pass')
    user.first_name = 'Youssef'
    user.last_name = 'Sioufy'
    user.save()
    abstract_user = AbstractUser(user=user, reviews_notification=0, connections_notification=0, messages_notification=0)
    abstract_user.save()
    sioufy = Teacher(abstract_user=abstract_user,
                    dob='1988-1-27', gender='Male', experience='I started playing the electric guitar when I was six and I didn\'t put it down since!',
                    favourite_genre='Fusion Jazz, Rock, and Experimental', instrument_played='Electric guitar',
                    jamming_style='Well, I mix Jazz with other types of music',
                    teaches='Electric Guitar', HOF=True, reviews=0, photo=photo)
    sioufy.save()
    
    photo = Photo(path=STATIC_URL + 'uploaded/baseimage.jpg')
    photo.save()
    user = User.objects.create_user('BigPaul', 'paul.herrman@gmail.com', 'pass')
    user.first_name = 'Paul'
    user.last_name = 'Herrman'
    user.save()
    abstract_user = AbstractUser(user=user, reviews_notification=0, connections_notification=0, messages_notification=0)
    abstract_user.save()
    pauline = Teacher(abstract_user=abstract_user,
                      dob='1954-1-5', gender='Male',
                      experience='12 years playing drums, 5 of them teaching.',
                      favourite_genre='trance', instrument_played='Drums, Guitar, and my own voice ;)',
                      jamming_style='Inspired by Elvis and other great music figures of my time',
                      teaches='Drums', HOF=False, reviews=0, photo=photo)
    pauline.save()
    
    return HttpResponse("Dummy data created successfully")

''''
author:Nader
date: 18.02.12
desc: Directs to editing info page
params: HttpRequest request
'''
def loadEditInfo(request):
    abstract_user = AbstractUser.objects.get(user=request.user)
    
    teachers = Teacher.objects.filter(abstract_user=abstract_user)
    students = Student.objects.filter(abstract_user=abstract_user)
    institutes = Institute.objects.filter(abstract_user=abstract_user)
    
    if teachers:
        userType = teachers[0]
        category = 'teacher'
    elif students:
        userType = students[0]
        category = 'student'
    elif institutes:
        userType = institutes[0]
        category = 'institute'
    else:
        print "User is not set to a TEACHER/STUDENT/INSTITUTE object"
    print category
    return render_to_response('editInfo.html', {'user':request.user, 'userType':userType, 'category':category, 'profileOwner':True, 'currentUser':getUser(request.user, False)}, context_instance=RequestContext(request))

'''
author:Nader
date:18.02.12
desc: gets params of user info and saves it, then redirects to profile
params: HttpRequest request
POSTparams: username, password, etc. (user info)
'''
def editInfo(request): 
    if request.POST:
        user = request.user
        abstract_user = AbstractUser.objects.get(user=user)
        try:
            student = Student.objects.get(abstract_user=abstract_user)
            form2 = StudentForm(request.POST, instance=student)
            form1 = MyUserChangeFormName(request.POST, instance=user)
        except (KeyError, Student.DoesNotExist):
            try:
                teacher = Teacher.objects.get(abstract_user=abstract_user)
                form2 = TeacherForm(request.POST, instance=teacher)
                form1 = MyUserChangeFormName(request.POST, instance=user)
            except (KeyError, Teacher.DoesNotExist):
                institute = Institute.objects.get(abstract_user=abstract_user)
                form2 = InstituteForm(request.POST, instance=institute)
                form1 = MyUserChangeForm(request.POST, instance=user)
        if form1.is_valid() and form2.is_valid():
            form1.save()
            form2.save()
            return index(request)
    else:
        user = request.user
        abstract_user = AbstractUser.objects.get(user=user)
        try:
            student = Student.objects.get(abstract_user=abstract_user)
            form2 = StudentForm(instance=student)
            form1 = MyUserChangeFormName(instance=user)
        except (KeyError, Student.DoesNotExist):
            try:
                teacher = Teacher.objects.get(abstract_user=abstract_user)
                form2 = TeacherForm(instance=teacher)
                form1 = MyUserChangeFormName(instance=user)
            except (KeyError, Teacher.DoesNotExist):
                institute = Institute.objects.get(abstract_user=abstract_user)
                form2 = InstituteForm(instance=institute)
                form1 = MyUserChangeForm(instance=user)
    return render_to_response('editInfo.html', {'form1':form1, 'form2':form2, 'user':user, 'profileOwner':True, 'currentUser':getUser(request.user, False)}, context_instance=RequestContext(request))
    
    '''
    user = request.user
    
    password = request.POST['password']
    if password:
        user.set_password(password)
        
    user.username = request.POST['username']
    user.first_name = request.POST['first_name']
    user.last_name = request.POST['last_name']
    user.email = request.POST['email']
    user.save()
    
    abstract_user = AbstractUser.objects.get(user=user)
    
    teachers = Teacher.objects.filter(abstract_user=abstract_user)
    students = Student.objects.filter(abstract_user=abstract_user)
    institutes = Institute.objects.filter(abstract_user=abstract_user)
    
    if teachers:
        teacher = teachers[0]
        teacher.dob = request.POST['dob']
        teacher.gender = request.POST['gender']
        teacher.experience = request.POST['experience']
        teacher.favourite_genre = request.POST['favourite_genre']
        teacher.instrument_played = request.POST['instrument_played']
        teacher.jamming_style = request.POST['jamming_style']
        teacher.save()
    elif students:
        student = students[0]
        student.dob = request.POST['dob']
        student.gender = request.POST['gender']
        student.experience = request.POST['experience']
        student.favourite_genre = request.POST['favourite_genre']
        student.instrument_played = request.POST['instrument_played']
        student.jamming_style = request.POST['jamming_style']
        student.save()
    elif institutes:
        institute = institutes[0]
    else:
        print "User is not set to a TEACHER/STUDENT/INSTITUTE object"

    return render_to_response('profile.html', {'error_message':"Your personal information has been updated successfully"}, context_instance=RequestContext(request))
    '''